<!-- MapContainer.vue -->
<template>
  <div class="map-container" id="map"></div>
</template>

<script>
import {Map} from '@/utils/map';
import mapTool from '@/utils/map';
import h3tools from "@/utils/h3tools";
import * as maptalks from 'maptalks';

export default {
  name: 'MapContainer',
  data() {
    return {
      mapInstance: null,  // 地图实例
      isSelectingPoint: false,  // 是否处于选点模式
      isDrawingPolygon: false,   // 是否处于绘制多边形模式
      drawTool: null,           // 绘制工具
      polygonLayer: null,       // 多边形图层
      polygonGeometries: {},     // 存储多边形几何对象 {name: geometry}
      pendingPolygonName: null  // 待命名的多边形名称
    };
  },
  mounted() {
    // 初始化地图（在DOM加载完成后）
    this.mapInstance = new Map();
    this.mapInstance.initMap();
    // 添加地图点击事件监听
    this.mapInstance.mapView.on('click', this.onMapClick);
  },
  beforeDestroy() {
    // 销毁地图实例，避免内存泄漏
    if (this.mapInstance?.mapView) {
      this.mapInstance.mapView.remove();
    }
    // 清理绘制工具
    if (this.drawTool) {
      this.drawTool.remove();
      this.drawTool = null;
    }
    // 清理图层
    if (this.polygonLayer) {
      this.polygonLayer.remove();
      this.polygonLayer = null;
    }
  },
  methods: {
    // 启用选点模式
    enablePointSelection() {
      this.isSelectingPoint = true;
    },
    // 禁用选点模式
    disablePointSelection() {
      this.isSelectingPoint = false;
    },
    // 处理地图点击事件
    onMapClick(event) {
      if (this.isSelectingPoint) {
        // 获取点击坐标
        const coordinate = event.coordinate;
        // 发送坐标到父组件
        this.$emit('mapClick', {lng: coordinate.x,lat: coordinate.y});
      }
    },
    // 开始绘制多边形
    startPolygonDrawing() {
      this.isDrawingPolygon = true;
      const result = mapTool.startPolygonDrawing(
          this.mapInstance.mapView,
          (coordinates, geometry) => {
            // 生成临时名称
            this.pendingPolygonName = 'pending_' + Date.now();
            this.polygonGeometries[this.pendingPolygonName] = geometry;
            // 将坐标发送到父组件，再由父组件传递给LeftPanel
            this.$emit('polygonCoordinatesUpdated', coordinates);
          }
      );
      // 保存返回的图层和绘制工具引用
      this.polygonLayer = result.polygonLayer;
      this.drawTool = result.drawTool;
    },
    // 停止绘制多边形
    stopPolygonDrawing() {
      this.isDrawingPolygon = false;
      if (this.drawTool) {
        this.drawTool.disable();
        this.drawTool.remove();
        this.drawTool = null;
      }
      document.getElementById('map').style.cursor = '';
    },
    // 根据名称删除多边形
    removePolygonByName(name) {
      if (this.polygonGeometries[name] && this.polygonLayer) {
        this.polygonLayer.removeGeometry(this.polygonGeometries[name]);
        // 从存储中删除
        delete this.polygonGeometries[name];
      }
    },
    // 重命名多边形
    renamePolygon(oldName, newName) {
      if (this.polygonGeometries[oldName]) {
        // 将几何对象移到新名称下
        this.polygonGeometries[newName] = this.polygonGeometries[oldName];
        delete this.polygonGeometries[oldName];
      }
    },
    // 聚焦到多边形区域
    focusPolygonArea(coordinates) {
      mapTool.focusPolygonArea(coordinates, this.mapInstance)
    },
    // 清除绘制的多边形
    clearPolygons() {
      if (this.polygonLayer) {
        this.polygonLayer.clear();
        // 同时清空存储的几何对象
        this.polygonGeometries = {};
      }
    },
    // 绘制网格
    drawGridsOnMap(h3Indexes){
      // 创建或获取专门用于显示网格的图层
      let gridLayer = this.mapInstance.mapView.getLayer('grid-layer');
      if (!gridLayer) {
        gridLayer = new maptalks.VectorLayer('grid-layer');
        this.mapInstance.mapView.addLayer(gridLayer);
      }
      // 清除之前的网格
      gridLayer.clear();
      // 根据h3Indexes向后端发送请求，获取格网属性字典{h3index:attribute}
      h3tools.getCellsAttributes(h3Indexes);
      // 为每个H3索引创建六边形
      h3Indexes.forEach(h3Index => {
        const hexagonBoundary = h3tools.cellToBoundary(h3Index); // lat,lng
        const coordinates = hexagonBoundary.map(coordinate => [coordinate[1], coordinate[0]]);
        new maptalks.Polygon([coordinates], {
          symbol: {
            lineColor: '#0000FF',      // 边框颜色（蓝色）
            lineWidth: 0.1,              // 边框粗细
            polygonFill: '#0000FF',    // 填充颜色
            polygonOpacity: 0.2        // 填充透明度
          }
        }).addTo(gridLayer);
      });
    }
  }
};
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
</style>
